package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.DealerBaseInfo;

public class FindDealerActivity extends BaseActivity implements
		OnItemClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.base_list_search);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.title)).setText("找经销商");
		showBackButton();
		this.list1 = ((ListView) findViewById(R.id.list1));
		this.list1.setOnItemClickListener(this);
		final EditText localEditText = (EditText) findViewById(R.id.searchKey);

		// localEditText.setOnKeyListener(new OnKeyListener() {
		//
		// @Override
		// public boolean onKey(View v, int keyCode, KeyEvent event) {
		//
		// if (KeyEvent.KEYCODE_ENTER == keyCode) {
		//
		// InputMethodManager localInputMethodManager = (InputMethodManager) v
		// .getContext().getSystemService("input_method");
		// if (localInputMethodManager.isActive())
		// localInputMethodManager.hideSoftInputFromWindow(
		// v.getApplicationWindowToken(), 0);
		// }
		//
		// return false;
		// }
		// });

		Button button = (Button) findViewById(R.id.searchButton1);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// 隐藏软键盘
				InputMethodManager localInputMethodManager = (InputMethodManager) v
						.getContext().getSystemService("input_method");
				if (localInputMethodManager.isActive())
					localInputMethodManager.hideSoftInputFromWindow(
							v.getApplicationWindowToken(), 0);

				// 获取搜索的关键字

				String searchKey = localEditText.getText().toString();

				if (searchKey.trim().length() == 0) {
					Toast.makeText(FindDealerActivity.this, "请输入关键字",
							Toast.LENGTH_SHORT).show();
					return;
				}
				AsyncTask<String, String, ArrayList<DealerBaseInfo>> task = new AsyncTask<String, String, ArrayList<DealerBaseInfo>>() {

					@Override
					protected ArrayList<DealerBaseInfo> doInBackground(
							String... params) {

						/**
						 * <keyWords>string</keyWords>
						 * <pageIndex>string</pageIndex>
						 * <pageSize>string</pageSize>
						 */
						NetworkProgressUtils utils = NetworkProgressUtils
								.getInstance();
						HashMap<String, String> allParams = new HashMap<String, String>();

						allParams.put("keyWords", params[0]);
						allParams.put("pageIndex", 1 + "");
						allParams.put("pageSize", 20 + "");
						publishProgress("");
						Object o = utils.getWebservicesByData(
								ConstantUtils.NAME_SPACE,
								ConstantUtils.ALL_METHROD_NAME.get(28),
								ConstantUtils.NAME_SPACE
										+ ConstantUtils.ALL_METHROD_NAME
												.get(28),
								ConstantUtils.GET_DEALERS_BY_KEYWORDS_URL,
								allParams);

						// System.out.println(o);

						ArrayList<DealerBaseInfo> all = utils
								.parseDealerBaseInfoBySearch(o.toString());

						// System.out.println(all);

						return all;

					}

					@Override
					protected void onProgressUpdate(String... values) {

						showLoading("正在搜索");
						super.onProgressUpdate(values);
					}

					@Override
					protected void onPostExecute(
							ArrayList<DealerBaseInfo> result) {

						hideLoading();
						System.out.println("result==" + result);
						if (result != null && result.size() != 0) {

							FindDealerAdapter adapter = new FindDealerAdapter(
									result);
							list1.setAdapter(adapter);
						} else {
							Toast.makeText(FindDealerActivity.this,
									"暂无查询结果,请尝试更换关键字再次搜索！", Toast.LENGTH_SHORT)
									.show();
						}
						super.onPostExecute(result);
					}
				};

				task.execute(searchKey);

			}
		});
	}

	private ListView list1;

	private class FindDealerAdapter extends BaseAdapter {

		private ArrayList<DealerBaseInfo> all = null;

		public FindDealerAdapter(ArrayList<DealerBaseInfo> all) {

			this.all = all;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return all.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return all.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.dealer_search_items, null);
			}

			DealerBaseInfo d = all.get(position);
			String s = d.getUserimg();
			String downloadUrl = null;
			if (s.indexOf("aodi") >= 0) {
				downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL_NEW;
			} else {
				downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL;
			}
			String imgUploadPath = downloadUrl + d.getUserimg();
			ImageView image = (ImageView) convertView
					.findViewById(R.id.itemAvatar);

			BitmapUtils bitmapUtils = new BitmapUtils(getApplicationContext());

			// 加载网络图片
			bitmapUtils.display(image, imgUploadPath);

			TextView textName = (TextView) convertView
					.findViewById(R.id.itemName);
			textName.setText(d.getCompname());
			TextView textIntro = (TextView) convertView
					.findViewById(R.id.itemBrand);
			textIntro.setText(d.getIntro());
			return convertView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View v, int position,
			long id) {

		DealerBaseInfo d = (DealerBaseInfo) adapterView.getAdapter().getItem(
				position);
		Intent intent = new Intent();
		intent.setClass(this, DealerPageActivity.class);
		intent.putExtra("bId", d.getId());
		startActivity(intent);
		finish();
	}
}
